package com.test.redis;

import java.util.List;
import java.util.Objects;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class WatchExample {
    private Jedis jedis;

    public WatchExample(Jedis jedis) {
        this.jedis = jedis;
    }

    public int doubleAccount(String userId) {
        String key = keyFor(userId);
        while (true) {
            jedis.watch(key);
            int value = Integer.parseInt(Objects.toString(jedis.get(key), "1"));
            value *= 2;
            Transaction transaction = jedis.multi();
            transaction.set(key, String.valueOf(value));
            List<Object> results = transaction.exec();
            if (results != null) {
                // 成功了
                break;
            }
        }
        // 重新获取结果
        return Integer.parseInt(jedis.get(key));
    }

    private String keyFor(String userId) {
        return String.format("account_%s", userId);
    }
}
